var mlhAPI = function(){
    //путь к серверу
    var url = '/api.php';
    //id магазина
    var shop = false;
    var pack = [];
    var cache = {};
    var pack_started = 0;
    this.options = {
        cache:true
    }
    //функция отправляющая запрос
    //mode - тип запроса (get, post)
    //params - get параметры
    //callback - функция возврата
    var ajax = function(mode, params, callback){
        if (!params) {
            //если нет параметров то ничего не вызываем
            return;
        }
        if (pack_started == 1){
            //если включен сборщик пакетов то запихиваем в список
            pack.push(
            {
                p: jQuery.param(params),
                callback: callback
            });
            return;
        }
        if(params['requestType'])delete(params['requestType']);
        var this_ = mlhAPI;
        var success = function(data){
            if (data['tableData']){
                data = this_.convertTable(data['tableData']);
            }
            callback(
            {
                result:'success',
                data: data
            }
            );
        }
        var needCache = this_.options.cache;
        //указываем get_nc если не хотим кешировать данные
        if (mode=='get_nc'){
            needCache = false;
            mode='get';
        }
        if (mode=='get') {
            var stringParams = jQuery.param(params);
            if(cache[stringParams]){
                console.log('Берем данные из кеша: ' + stringParams);
                success(cache[stringParams]);
                return;
            }
        }
        //указываем get_rc если не хотим брать данные из кеша, но хотим чтоб они туда попали
        if (mode=='get_rc'){
            console.log('Записываем кеш');
            mode='get';
        }
        jQuery.ajax(
        {
            url: url,
            dataType: 'json',
            type: mode,
            data: params,
            success: function(responseData) {
                if(needCache) {
                    if(this.type != 'POST') {
                        console.log(this.url);
                        cache[this.url.replace(url+'?','')] = responseData;
                    }
                }
                success(responseData);
            },
            error: function(responseData) {
                callback(
                {
                    result:'error',
                    data: responseData.responseText
                }
                );
            }
        });
    }
    this.cleanCache = function(mask){
        for(k in cache){
            if(k.indexOf(mask)>-1)cache[k] = null;
        };
    }
    //конвертирование данных переданных как таблица
    this.convertTable = function(convertData) {
        var returnData = [];
        for (var i in convertData[1]) {
            var row = {};
            for (var k in convertData[0]) {
                row[convertData[0][k]] = convertData[1][i][k];
            }
            returnData.push(row);
        }
        return returnData;
    }
    //получить ID магазина
    this.setShop = function(s) {
        shop = s;
        return this;
    }
    //получить данные по get
    this.get = function(params, callback){
        var mode = params['requestType'] || 'get';
        ajax(mode, params, callback);
        return this;
    }
    //получить данные по post
    this.post = function(params, callback){
        var mode = params['requestType'] || 'post';
        ajax(mode, params, callback);
        return this;
    }
    //получить данные по праметрам
    this.data = function(module, view, custom, callback) {
        var params = {
            c: module,
            v: view
        };
        if(custom) params['cu'] = custom;
        if (shop) {
            params['shop'] = shop;
        }
        return ajax('get', params, callback ? callback : function(){});
    }
    //отправить данные без колбека
    this.reqest = function(params){
        ajax('get', params, function(){});
    }
    this.startPack = function(){
        if(pack_started > 0) return this;
        pack_started = 1;
        return this;
    }
    this.endPack = function(){
        if(pack_started !=1) return this;
        pack_started = 2;
        var send_text = [];
        var this_ = mlhAPI;
        if(!pack.length) return this;
        for(var i in pack) send_text.push(pack[i].p);
        this.post(jQuery.param({pack:send_text}), function(data){
            pack_started = 0;
            for (var i = 0; i<pack.length; i++){
                var returnData = data.result == 'error' ? data : data.data[i];
                if (returnData['tableData']){
                    returnData = this_.convertTable(returnData['tableData']);
                }
                pack[i].callback(
                {
                    result:data.result,
                    data: returnData
                })
            }
            pack = [];
        })
        return this;
    }
    this.showCache = function(){console.log(cache)}
    var APIaction = function(data){
        var callback = data['callback']?data['callback']:function(){};
        var type = data['requestType']?data['requestType']:'get';
        delete data['callback'];
        delete data['requestType'];
        if(undefined == data['s'] && location.host.split('.').length>2) data['s'] = location.host.split('.')[0];
        (function(type, data, callback){
            ajax(type, data, callback);
        })(type, data, callback);
    }
	
    //Базовые
    var mainActions = function(){
        this.actions = function(data){
        	jQuery.extend(data, {
	            c: 'main'
	        });
        	APIaction(data);
        }

        this.logout = function(data){
            jQuery.extend(data, {
                v: 'logout',
                requestType: 'get_nc'
            });
            this.actions(data);
            return true;
        }

        this.login = function(data){
            if(!data['email'] || !data['password']) return false;
            jQuery.extend(data, {
                v: 'login',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }
        this.info = function(data){
        	jQuery.extend(data, {
                v: 'info',
                requestType: 'get_nc'
            });
            this.actions(data);
            return true;
        }
        this.shop = function(data){
            jQuery.extend(data, {
                v: 'shop',
                requestType: 'get_nc'
            });
            this.actions(data);
            return true;
        }
    }
    this.main = new mainActions();
    
    //Категории
    var categoryActions = function(){
        this.actions = function(data){
        	jQuery.extend(data, {
	            c: 'category'
	        });
        	APIaction(data);
        }

        this.getTree= function(data){
            jQuery.extend(data, {
                v: 'JSONList',
                asTable: 1
            });
            this.actions(data);
            return true;
        }
        
        this.getList= function(data){
            jQuery.extend(data, {
                v: 'JSONList',
                tree: 0
            });
            this.actions(data);
            return true;
        }

        this.get = function(data){
            if(data['id'] == undefined && !data['model']) return false;
            jQuery.extend(data, {
                v: 'display'
            });
            this.actions(data);
            return true;
        }

        this.set = function(data){
            jQuery.extend(data, {
                v: 'save',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.del = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'delete'
            });
            this.actions(data);
            return true;
        }
    }
    this.category = new categoryActions();
    
    //Артикли
    var articleActions = function(){
        this.actions = function(data){
        	jQuery.extend(data, {
	            c: 'article'
	        });
        	APIaction(data);
        }
        this.getComments = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
	            h: 'comments',
                v: 'getComments',
                model: 'article'
	        });
        	APIaction(data);
            return true;
        }
        this.setComment = function(data){
            if(!data['model_id']) return false;
            jQuery.extend(data, {
	            c: 'comment',
                v: 'save',
                model: 'article',
                requestType: 'post'
	        });
        	APIaction(data);
            return true;
        }
        this.delComment = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
	            c: 'comment',
                v: 'delete'
	        });
        	APIaction(data);
            return true;
        }
		this.getNews = function(data){
        	if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'show',
                model: 'news'
            });
            this.actions(data);
            return true;
        }
        this.getList = function(data){
        	if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'show'
            });
            this.actions(data);
            return true;
        }
        this.get = function(data){
            if(!data['id'] && !data['category_id']) return false;
            jQuery.extend(data, {
                v: 'display'
            });
            this.actions(data);
            return true;
        }

        this.set = function(data){
            jQuery.extend(data, {
                v: 'save',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.del = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'delete'
            });
            this.actions(data);
            return true;
        }
    }
    this.article = new articleActions();
    
    //Регионы
    var regionActions = function(){
        this.actions = function(data){
        	jQuery.extend(data, {
	            c: 'region'
	        });
        	APIaction(data);
        }
		this.getCountryList = function(callback){
            this.actions({
                callback: callback,
                v: 'regionList',
                asTable: 1
            });
            return true;
        }
        this.getCityList = function(data){
        	if(!data['country'])return false;
            data['parent_id'] = data['country'];
            delete data['country'];
            jQuery.extend(data, {
                v: 'regionList',
                asTable: 1
            });
            this.actions(data);
            return true;
        }
    }
    this.region = new regionActions();

    //Валюты
    var currencyActions = function(){
        this.actions = function(data){
        	jQuery.extend(data, {
	            c: 'currency'
	        });
        	APIaction(data);
        }
		this.getList = function(data){
            jQuery.extend(data, {
	            v: 'show'
	        });
            this.actions(data);
            return true;
        }
    }
    this.currency = new currencyActions();

    //Теги
    var tagActions = function(){
        this.actions = function(data){
        	jQuery.extend(data, {
	            c: 'tag'
	        });
        	APIaction(data);
        }
		this.getList = function(data){
            jQuery.extend(data, {
	            v: 'show'
	        });
            this.actions(data);
            return true;
        }
        this.autoconplete = function(data){
            jQuery.extend(data, {
                v: 'autocomplete',
                h: 'tag'
            });
            APIaction(data);
            return true;
        }
    }
    this.tag = new tagActions();

    //Пользователи
    var usersActions = function(){
        this.actions = function(data){
            jQuery.extend(data, {
                c: 'user'
            });
            APIaction(data);
        }
        this.get = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'display',
            });
            this.actions(data);
            return true;
        }
        this.getAddress = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'getAddress',
            });
            this.actions(data);
            return true;
        }
    }
    this.user = new usersActions();

    //Продукты
    var productActions = function(){
        this.actions = function(data){
            jQuery.extend(data, {
                c: 'product'
            });
            APIaction(data);
        }
        this.getComments = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                h: 'comments',
                v: 'getComments',
                model: 'product'
            });
            APIaction(data);
            return true;
        }
        this.setComment = function(data){
            if(!data['model_id']) return false;
            jQuery.extend(data, {
                c: 'comment',
                v: 'save',
                model: 'product',
                requestType: 'post'
            });
            APIaction(data);
            return true;
        }
        this.delComment = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                c: 'comment',
                v: 'delete'
            });
            APIaction(data);
            return true;
        }
        this.getListByShop = function(data){
            if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'showByShop'
            });
            this.actions(data);
            return true;
        }
        this.getList = function(data){
            if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'show'
            });
            this.actions(data);
            return true;
        }
        this.get = function(data){
            if(!data['id'] && !data['category_id'] && !data['tag_id']) return false;
            jQuery.extend(data, {
                v: 'display'
            });
            this.actions(data);
            return true;
        }

        this.set = function(data){
            jQuery.extend(data, {
                v: 'save',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.del = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'delete'
            });
            this.actions(data);
            return true;
        }
    }
    this.product = new productActions();

    //параметры
    var paramActions = function(){
        this.actions = function(data){
            jQuery.extend(data, {
                c: 'param'
            });
            APIaction(data);
        }
        this.getList = function(data){
            if(!data['category_id']) return false;
            if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'getListByCategory'
            });
            this.actions(data);
            return true;
        }
        this.get = function(data){
            if(!data['category_id']) return false;
            jQuery.extend(data, {
                v: 'display'
            });
            this.actions(data);
            return true;
        }

        this.set = function(data){
            jQuery.extend(data, {
                v: 'save',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.del = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'delete'
            });
            this.actions(data);
            return true;
        }
    }
    this.param = new paramActions();

    //заказы
    var orderActions = function(){
        this.actions = function(data){
            jQuery.extend(data, {
                c: 'order'
            });
            APIaction(data);
        }
        this.getList = function(data){
            if(!data['shop']) return false;
            if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'show'
            });
            this.actions(data);
            return true;
        }
        this.get = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'display'
            });
            this.actions(data);
            return true;
        }

        this.set = function(data){
            jQuery.extend(data, {
                v: 'save',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.new = function(data){
            jQuery.extend(data, {
                v: 'create',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.del = function(data){
            if(!data['order_id']) return false;
            jQuery.extend(data, {
                v: 'delete'
            });
            this.actions(data);
            return true;
        }

        this.shipMethods = function(data){
            jQuery.extend(data, {
                v: 'getShipMethods'
            });
            this.actions(data);
            return true;
        }

        this.paymentMethods = function(data){
            jQuery.extend(data, {
                v: 'getPaymentMethods'
            });
            this.actions(data);
            return true;
        }

    }
    this.order = new orderActions();
    
    //заказы
    var mailActions = function(){
        this.actions = function(data){
            jQuery.extend(data, {
                c: 'mail'
            });
            APIaction(data);
        }
        this.getList = function(data){
            if(!data['pagination'])data['asTable']=1;
            jQuery.extend(data, {
                v: 'show'
            });
            this.actions(data);
            return true;
        }
        this.get = function(data){
            if(!data['id']) return false;
            jQuery.extend(data, {
                v: 'display'
            });
            this.actions(data);
            return true;
        }

        this.set = function(data){
            jQuery.extend(data, {
                v: 'save',
                requestType: 'post'
            });
            this.actions(data);
            return true;
        }

        this.del = function(data){
            if(!data['mail_id']) return false;
            jQuery.extend(data, {
                v: 'delete'
            });
            this.actions(data);
            return true;
        }
    }
    this.mail = new mailActions();
}

mlhAPI = new mlhAPI();
jQuery(document).trigger('mlhAPI_loaded');